package com.chuangke.lowcode.component.delete;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.IService;
import com.chuangke.common.constant.ColumnConstants;
import com.chuangke.common.utils.SpringContextUtil;
import com.chuangke.lowcode.LowCodeContext;
import com.chuangke.lowcode.component.ProgressComponent;
import com.chuangke.lowcode.model.EntityModel;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.List;

/**
 * 根据单据编号删除单据
 */
@Component
@Transactional(rollbackFor = Throwable.class)
public class BillDeleteComponent implements ProgressComponent {

    public void process(LowCodeContext modelContext) {
        List<String> billIdList = modelContext.getDatas();

        delete(Collections.singletonList(modelContext.getEntityModel()), billIdList);
    }

    /**
     * 根据单据编号删除单据
     *
     * @param models
     * @param billIdList
     */
    @SuppressWarnings({"rawtypes", "unchecked"})
    private void delete(List<EntityModel> models, List<String> billIdList) {
        for (EntityModel model : models) {
            IService service = SpringContextUtil.getDaoBean(model.getEntityClass());

            QueryWrapper qw = new QueryWrapper();
            qw.in(ColumnConstants.COL_BILL_ID, billIdList);
            service.remove(qw);

            if (!CollectionUtils.isEmpty(model.getChildren())) {
                delete(model.getChildren(), billIdList);
            }
        }
    }

}
